package com.tdtxdcxm.mynotepad.slice;

import com.tdtxdcxm.mynotepad.ResourceTable;
import com.tdtxdcxm.mynotepad.notedata.NoteDataManager;
import com.tdtxdcxm.mynotepad.notedetails.NoteDetailInfoList;
import com.tdtxdcxm.mynotepad.record.RecordComponentItem;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.dialog.IDialog;
import ohos.agp.window.dialog.ToastDialog;
import ohos.media.image.ImagePacker;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.photokit.metadata.AVStorage;
import ohos.multimodalinput.event.MmiPoint;
import ohos.multimodalinput.event.TouchEvent;
import ohos.utils.net.Uri;

import java.io.*;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;


public class EditAbilitySlice extends AbilitySlice {

    private File thisnotefoldername;//保存正在编辑笔记到某个文件夹，该文件夹的File实例
    private float x1,x2,y1,y2;

    //用于记录当前编辑笔记的组件顺序。例如：当前编辑区域按顺序有一个输入框-图片-图片-输入框，则recordlist按此顺序记录。
    private ArrayList<RecordComponentItem> recordlist = new ArrayList<>();


    private DirectionalLayout edit_rootdl,edit_rootdl_ddl3;

    private Button edit_rootdl_ddl1_1_nobut,edit_rootdl_ddl1_1_savebut;

    private ScrollView edit_rootdl_ddl2_scrollview;
    private DirectionalLayout edit_rootdl_ddl2_scrollview_ddl;
    private TextField ddl2_scrollview_ddl_solidtfd;

    private Button edit_rootdl_ddl3_clearbut,edit_rootdl_ddl3_wantimagebut;

    boolean isgetimage = false;//判断是否成功从相册或文件夹中获取到图片文件
    boolean issave = false;//判断是不是第一次保存，如果是第一次保存该笔记内容，则首先生成一个文件夹，该文件中将存放文本和图片文件
    boolean issavebutpress = false;//判断笔记内容变化后，是否点击了保存按钮；笔记内容变化：各个文本输入框内容变化、图片的插入或删除、输入框的插入或删除


    public void checkPrintlnRecordList() {
        for(int j = 0;j < recordlist.size();j++){
            if(j == 0){
                System.out.println("开始检查recordlist值：");
            }
            if(j == recordlist.size() - 1){
                System.out.println(j+"----->>>"+recordlist.get(j).getName());
                System.out.println("检查recordlist值完成！");
                continue;
            }
            System.out.println(j+"----->>>"+recordlist.get(j).getName());
        }
    }
    public void clearRecordListComponents(){
        for(int i = 1;i < recordlist.size();i++){
            edit_rootdl_ddl2_scrollview_ddl.removeComponent(recordlist.get(i).component);
        }
        recordlist.clear();
        recordlist.add(new RecordComponentItem(edit_rootdl_ddl2_scrollview_ddl,0));
        checkPrintlnRecordList();
    }

    private void selectPicture(){
        //参照教程
        Intent intent = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withAction("android.intent.action.GET_CONTENT")
                .build();
        intent.setOperation(operation);
        intent.addFlags(Intent.FLAG_NOT_OHOS_COMPONENT);
        intent.setType("image/*");
        startAbilityForResult(intent,9);
    }

    @Override
    public void onAbilityResult(int requestCode, int resultCode, Intent resultData){
        //参照教程修改
        if(resultData == null){
            isgetimage = false;
            return;
        }

        if(requestCode == 9){
            DirectionalLayout directionalLayout = getNewImage();
            String chooseImgUri=resultData.getUriString();

            DataAbilityHelper helper=DataAbilityHelper.creator(this.getContext());
            ImageSource imageSource = null;
            String chooseImgId=null;
            if(chooseImgUri.lastIndexOf("%3A")!=-1){
                chooseImgId = chooseImgUri.substring(chooseImgUri.lastIndexOf("%3A")+3);
            }
            else {
                chooseImgId = chooseImgUri.substring(chooseImgUri.lastIndexOf('/')+1);
            }

            Uri uri=Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI,chooseImgId);
            try {
                FileDescriptor fd = helper.openFile(uri, "r");
                imageSource = ImageSource.create(fd, null);
                PixelMap pixelMap = imageSource.createPixelmap(null);
                ((Image)directionalLayout.getComponentAt(0)).setPixelMap(pixelMap);

                System.out.println("isgetimage is :"+isgetimage);

                edit_rootdl_ddl2_scrollview_ddl.addComponent(directionalLayout);
                recordlist.add(new RecordComponentItem(directionalLayout,1));

                directionalLayout = getNewTextField();
                edit_rootdl_ddl2_scrollview_ddl.addComponent(directionalLayout);
                recordlist.add(new RecordComponentItem(directionalLayout,0));

                isgetimage = false;
            }
            catch (Exception e) {
                e.printStackTrace();
            }
            finally {
                if (imageSource != null) {
                    imageSource.release();
                }
            }
        }

    }

    public void toastShow(String s){
        ToastDialog toastDialog = new ToastDialog(this.getContext());
        toastDialog.setText(s);
        toastDialog.setTransparent(true);
        toastDialog.setDuration(100);
        toastDialog.setAlignment(LayoutAlignment.CENTER);
        toastDialog.show();
    }
    public void commonDialogRemoveShow(String title,String content,Component component){
        CommonDialog commonDialog = new CommonDialog(this.getContext());
        commonDialog.setTitleText(title);
        commonDialog.setContentText(content);
        commonDialog.setSize(500,400);
        commonDialog.setButton(1, "确认", new IDialog.ClickedListener() {
            @Override
            public void onClick(IDialog iDialog, int i) {
                int index = component.getComponentParent().getChildIndex(component);
                component.getComponentParent().removeComponent(component);
                recordlist.remove(index);

                checkPrintlnRecordList();//检查recordlist列表的值
                issavebutpress = false;//输入框发生删除，则视为笔记内容发生变化，将issavebutpress立即置为false
                commonDialog.destroy();
            }
        });
        commonDialog.setButton(2, "取消", new IDialog.ClickedListener() {
            @Override
            public void onClick(IDialog iDialog, int i) {

                commonDialog.destroy();
            }
        });

        commonDialog.show();
    }

    public DirectionalLayout getNewTextField(){
        DirectionalLayout directionalLayout = (DirectionalLayout) LayoutScatter.getInstance(this.getContext()).parse(ResourceTable.Layout_edit_textfield_sublayout,null,false);

        TextField textField= (TextField) directionalLayout.getComponentAt(0);
        Button button = (Button) directionalLayout.getComponentAt(1);

        button.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                commonDialogRemoveShow("文本删除提示","是否删除所指内容？",directionalLayout);
            }
        });
        textField.addTextObserver(new Text.TextObserver() {
            @Override
            public void onTextUpdated(String s, int i, int i1, int i2) {
                issavebutpress = false;//一旦检查到文本输入框内容发生变化，则立即将issavebutpress置为false
            }
        });
        textField.setTouchEventListener(new Component.TouchEventListener() {
            @Override
            public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
                if(touchEvent.getAction() == TouchEvent.PRIMARY_POINT_DOWN){
                    MmiPoint mmiPoint = touchEvent.getPointerPosition(0);
                    x1 = mmiPoint.getX();
                    y1 = mmiPoint.getY();
                }
                if(touchEvent.getAction() == TouchEvent.PRIMARY_POINT_UP){
                    MmiPoint mmiPoint = touchEvent.getPointerPosition(0);
                    x2 = mmiPoint.getX();
                    y2 = mmiPoint.getY();
                    if(x1 > x2 && Math.abs(y1 - y2) <= 100){
                        button.setVisibility(Component.VISIBLE);
                    }
                    if(x1 < x2 && Math.abs(y1 - y2) <= 100){
                        button.setVisibility(Component.HIDE);
                    }
                }
                return true;
            }
        });
        textField.setLongClickedListener(new Component.LongClickedListener() {
            @Override
            public void onLongClicked(Component component) {
                commonDialogRemoveShow("文本删除提示","是否删除所指内容？",directionalLayout);
            }
        });

        return directionalLayout;
    }

    public DirectionalLayout getNewImage(){
        DirectionalLayout directionalLayout = (DirectionalLayout) LayoutScatter.getInstance(this.getContext()).parse(ResourceTable.Layout_edit_image_sublayout,null,false);
        Image image = (Image) directionalLayout.getComponentAt(0);
        System.out.println("-------------->"+image);

        directionalLayout.setLongClickedListener(new Component.LongClickedListener() {
            @Override
            public void onLongClicked(Component component) {
                commonDialogRemoveShow("图片删除提示","是否删除所指图片？",directionalLayout);
                issavebutpress = false;//一旦图片从文本中删除，则视为笔记内容发生变化，立即将issavebutpress置为false
            }
        });
        image.setLongClickedListener(new Component.LongClickedListener() {
            @Override
            public void onLongClicked(Component component) {
                commonDialogRemoveShow("图片删除提示","是否删除所指图片？",directionalLayout);
                issavebutpress = false;//一旦图片从文本中删除，则视为笔记内容发生变化，立即将issavebutpress置为false
            }
        });

        return directionalLayout;
    }

    public void encodeAndSaveImage(PixelMap pixelMap,File thisnotefoldername,int orderfilename){
        ImagePacker imagePacker = ImagePacker.create();

        String filepath = Paths.get(thisnotefoldername.toString(),orderfilename+".jpeg").toString();
        File  targetfile = new File(filepath);

        try
        {
            FileOutputStream fileOutputStream = new FileOutputStream(targetfile);

            ImagePacker.PackingOptions packingOptions = new ImagePacker.PackingOptions();
            packingOptions.format = "image/jpeg";
            packingOptions.numberHint=1;
            packingOptions.quality = 100;

            imagePacker.initializePacking(fileOutputStream,packingOptions);
            imagePacker.addImage(pixelMap);
            imagePacker.finalizePacking();

            fileOutputStream.close();
        }
        catch (FileNotFoundException e){
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    public void saveTextField(File thisnotefoldername,TextField textField,int index){
        File file = new File(thisnotefoldername.toString()+"/"+index+".txt");
        try
        {
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(textField.getText().getBytes());
            fileOutputStream.flush();
            fileOutputStream.close();
        }
        catch (FileNotFoundException e){
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void showDir(){

        String DatabaseDir = this.getDatabaseDir().toString();
        String PreferencesDir = this.getPreferencesDir().toString();

        File DataDirfile = new File(this.getDataDir().toString()+"/usernote");
        DataDirfile.mkdir();//创建usernote文件夹

        NoteDataManager.isUserNoteExist();

        String noteeach = DataDirfile.toString();
        System.out.println("新建的笔记记录文件夹路径："+noteeach);
        String DataDir =  this.getDataDir().toString();

        String CacheDir = this.getCacheDir().toString();
        String CodeCacheDir = this.getCodeCacheDir().toString();
        String FilesDir = this.getFilesDir().toString();

        //String ExternalCacheDir = this.getExternalCacheDir().toString();
        //String ExternalFilesDir = this.getExternalFilesDir("hello").toString();

        File file = null;

        /*
        file = new File(this.getExternalCacheDir().getParent().toString()+"/want");
        try
        {
            file.mkdir();
        }
        catch (Exception e){
            e.printStackTrace();
        }
        */

        file = new File(this.getExternalCacheDir().getParent());
        String ss  = file.toString();
        System.out.println("ss--->>>"+ss);
        String[] slist = file.list();
        for(int i = 0;i < slist.length;i++){
            System.out.println("------->>>>>>"+slist[i]);
        }

        /*
        System.out.println("-----------------------------------------------");
        slist = this.getExternalCacheDir().list();
        System.out.println("slist.size():"+slist.length);
        for(int i = 0;i < slist.length;i++){
            System.out.println("------->>>>>>"+slist[i]);
        }

        System.out.println("外部应用私有ExternalCacheDir-->>"+ExternalCacheDir);
        System.out.println("外部应用私有ExternalFilesDir-->>"+ExternalFilesDir);
        System.out.println("-----------------------------------------------");
        */

        System.out.println("开始输出文件目录检查：");
        System.out.println("数据库DatabaseDir-->>"+DatabaseDir);
        System.out.println("偏好键值对数据库PreferencesDir-->>"+PreferencesDir);
        System.out.println("沙盒DataDir-->>"+DataDir);
        System.out.println("沙盒CacheDir-->>"+CacheDir);
        System.out.println("沙盒CodeCacheDir-->>"+CodeCacheDir);
        System.out.println("沙盒FilesDir-->>"+FilesDir);
        System.out.println("输出文件目录检查完成！");
    }

    public File createThisNoteFolder(){
        File file;
        Date date = new Date();//获取点击保存按钮时的时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");//对该时间按照“年月日”格式化
        String todayfoldername = simpleDateFormat.format(date);//将格式化后的日期字符串当作今日文件夹名称
        System.out.println("当前日期为---》"+todayfoldername);

        file = new File(this.getDataDir().toString()+"/usernote/"+todayfoldername);//获取当日文件夹的File实例
        if(file.exists() == false){
            //如果当日文件夹不存在，则说明用户今天第一次使用软件点击保存按钮，则需要创建当日文件夹
            file.mkdir();//创建该文件夹
        }

        String thisnotefoldername = file.toString()+"/"+String.valueOf(file.list().length+1);//给本次笔记命名一个文件夹名称
        System.out.println("thisnotefoldername-->>"+thisnotefoldername);
        file = new File(thisnotefoldername);//获得本次笔记文件夹File实例
        file.mkdir();//创建该文件夹,在当日文件夹中放置


        File check_usernote_folderlist = new File(this.getDataDir().toString()+"/usernote");
        String[] usernotelist = check_usernote_folderlist.list();
        for(int i = 0;i < usernotelist.length;i++){
            System.out.println("-------check usernote>>>>>>"+usernotelist[i]);
        }


        return file;
    }



    public void initEASliceComponents(){
        edit_rootdl = (DirectionalLayout) findComponentById(ResourceTable.Id_edit_rootdl);
        edit_rootdl_ddl1_1_nobut = (Button) findComponentById(ResourceTable.Id_edit_rootdl_ddl1_1_nobut);
        edit_rootdl_ddl1_1_savebut = (Button) findComponentById(ResourceTable.Id_edit_rootdl_ddl1_1_savebut);

        edit_rootdl_ddl2_scrollview = (ScrollView) findComponentById(ResourceTable.Id_edit_rootdl_ddl2_scrollview);
        edit_rootdl_ddl2_scrollview_ddl = (DirectionalLayout) findComponentById(ResourceTable.Id_edit_rootdl_ddl2_scrollview_ddl);

        ddl2_scrollview_ddl_solidtfd = (TextField) findComponentById(ResourceTable.Id_ddl2_scrollview_ddl_solidtfd);
        ddl2_scrollview_ddl_solidtfd.setHint("这里不能为空，非空才能保存！");
        recordlist.add(new RecordComponentItem(edit_rootdl_ddl2_scrollview_ddl,0));

        edit_rootdl_ddl3 = (DirectionalLayout) findComponentById(ResourceTable.Id_edit_rootdl_ddl3);
        edit_rootdl_ddl3_clearbut = (Button) findComponentById(ResourceTable.Id_edit_rootdl_ddl3_clearbut);
        edit_rootdl_ddl3_wantimagebut = (Button) findComponentById(ResourceTable.Id_edit_rootdl_ddl3_wantimagebut);

        /*<***********************************给顶部取消和保存设置监听器******************************/
        edit_rootdl_ddl1_1_nobut.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if(issavebutpress == false){
                    toastShow("未保存！");
                }
                else{
                    toastShow("已经保存！");
                }
                terminateAbility();
            }
        });
        edit_rootdl_ddl1_1_savebut.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if(recordlist.size() == 1 && ddl2_scrollview_ddl_solidtfd.getText().equals("")){
                    ddl2_scrollview_ddl_solidtfd.clearFocus();
                    toastShow("内容为空，不能保存！");
                    return;
                }
                if(issave == true){
                    NoteDataManager.deleteFolderFiles(thisnotefoldername);
                    System.out.println("已经删除了该笔记文件夹中所有txt和image！【Warning】");
                }
                if(issave == false){
                    thisnotefoldername =  createThisNoteFolder();
                    issave = true;
                }

                checkPrintlnRecordList();
                for(int i = 0;i < recordlist.size();i++){
                    if(recordlist.get(i).type == 1){
                        Image image= (Image)((DirectionalLayout)recordlist.get(i).component).getComponentAt(0);
                        encodeAndSaveImage(image.getPixelMap(),thisnotefoldername,i);
                    }
                    if(recordlist.get(i).type == 0){
                        TextField textField = (TextField) ((DirectionalLayout)recordlist.get(i).component).getComponentAt(0);
                        saveTextField(thisnotefoldername,textField,i);
                    }
                }

                String[] ls = thisnotefoldername.list();
                for(int i = 0;i < ls.length;i++){
                    System.out.println("检查--------------》》》》》》"+ls[i]);
                }

                NoteDataManager.generateUserNoteDir();
                NoteDataManager.checkUserNoteDir();
                toastShow("已经保存！");
                ddl2_scrollview_ddl_solidtfd.clearFocus();
                issavebutpress = true;//已经按了保存按钮
            }
        });
        /*************************************给顶部取消和保存设置监听器****************************>*/

        /*<********************************给底部清除、照片设置监听器****************************/
        edit_rootdl_ddl3_clearbut.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                ddl2_scrollview_ddl_solidtfd.clearFocus();
                ddl2_scrollview_ddl_solidtfd.setText("");

                clearRecordListComponents();
            }
        });

        edit_rootdl_ddl3_wantimagebut.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                selectPicture();
            }
        });
        /**********************************给底部清除、照片设置监听器**************************>*/

        /*<*****************************给固有文本输入框设置文本内容变化监听****************************/
        ddl2_scrollview_ddl_solidtfd.addTextObserver(new Text.TextObserver() {
            @Override
            public void onTextUpdated(String s, int i, int i1, int i2) {
                issavebutpress = false;//一旦固有存在的文本输入框内容发生变化，立即将issavebutpress置为false
                if(s.equals("") == false){
                    edit_rootdl_ddl3.setVisibility(Component.VISIBLE);
                    edit_rootdl_ddl1_1_savebut.setVisibility(Component.VISIBLE);
                }
                else{
                    edit_rootdl_ddl3.setVisibility(Component.HIDE);
                    edit_rootdl_ddl1_1_savebut.setVisibility(Component.HIDE);
                }
            }
        });
        /*******************************给固有文本输入框设置文本内容变化监听**************************>*/

    }


    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_edit);

        if(intent.getStringParam("type").equals("add")){
            initEASliceComponents();
        }
        if(intent.getStringParam("type").equals("detail")){
            File file = new File(intent.getStringParam("thisnotefoldername"));
            thisnotefoldername = file;
            issave = true;
            System.out.println("type:detail检查---》issave is:"+issave+",thisnotefoldername is:"+thisnotefoldername);
            initEASliceComponents();


            ArrayList<NoteDetailInfoList> noteDetailInfoLists = NoteDataManager.readSomeNoteDetails(file,this);

            for(int i = 0;i < noteDetailInfoLists.size();i++){
                if(i == 0){
                    ddl2_scrollview_ddl_solidtfd.setText((String) (noteDetailInfoLists.get(i).object));
                    continue;
                }
                if(noteDetailInfoLists.get(i).type == 0){
                    DirectionalLayout directionalLayout = getNewTextField();
                    TextField textField = (TextField) directionalLayout.getComponentAt(0);
                    textField.setText((String) (noteDetailInfoLists.get(i).object));
                    edit_rootdl_ddl2_scrollview_ddl.addComponent(directionalLayout);
                    recordlist.add(new RecordComponentItem(directionalLayout,0));
                }
                if(noteDetailInfoLists.get(i).type == 1){
                    DirectionalLayout directionalLayout = getNewImage();
                    Image image = (Image) directionalLayout.getComponentAt(0);
                    image.setPixelMap((PixelMap) (noteDetailInfoLists.get(i).object));
                    edit_rootdl_ddl2_scrollview_ddl.addComponent(directionalLayout);
                    recordlist.add(new RecordComponentItem(directionalLayout,1));
                }
            }
        }

        String[] permission = {"ohos.permission.READ_USER_STORAGE","ohos.permission.WRITE_USER_STORAGE"};
        requestPermissionsFromUser(permission,0);

        showDir();
    }

    @Override
    protected void onActive() {
        super.onActive();

    }

    @Override
    protected void onInactive() {
        super.onInactive();
    }

    @Override
    protected void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onBackground() {
        super.onBackground();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }
}
